/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rtech.billing.pdf.conversion;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
import com.rtech.billing.property.Constants;
import com.rtech.billing.property.PropertiesManager;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

/**
 *
 * @author rattank
 */
public class SimplePDFGenerator extends PDFGenerator {
    private String  filePath = null ;
    
    public String createPDF(String fileName , String fileContent , boolean headerRequired) {
        PdfWriter writer;
        this.filePath = PropertiesManager.getInstance().getPropertyValue(Constants.PROPERTY_TARGET_FILE_PATH);
        try {
            Document document = new Document();
            writer = PdfWriter.getInstance(document, new FileOutputStream(filePath+ fileName));
            writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
            writer.setPageEvent(new SimplePDFGenerator());
            document.setMargins(36, 36, 36, 54);
            // step 3:
            document.open();
            if(headerRequired){
                String  headerString = getHeaderElement() ;
                StringReader header = new StringReader(headerString);
                List<Element> headerElements = HTMLWorker.parseToList(header, null);
                for (Element element : headerElements) {
                    document.add(element);
                }

            }
            StringReader  reader = new StringReader(fileContent );

            List<Element> elements = HTMLWorker.parseToList(reader, null);

            for (Element element : elements) {
                document.add(element);
            }
            document.close();
        } catch (DocumentException ex) {
            ex.printStackTrace();
        }catch (IOException ex) {
                ex.printStackTrace();
        }


        return filePath + fileName;
    }
}
